/*
 * Copyright © 2004-2014 chenYuan. All rights reserved.
 * @Website:wwww.jspx.net
 * @Mail:39793751@qq.com
 * @author: chenYuan , 陈原
 * @License: Jspx.net Framework Code is open source (LGPL)，Jspx.net Framework 使用LGPL 开源授权协议发布。
 * @jvm:jdk1.6+  x86/amd64
 *
 */
package com.jspx.sober.transaction;


import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by IntelliJ IDEA.
 * User: chenYuan
 * Date: 2008-8-21
 * Time: 18:09:31
 * 事务池
 */
public class TransactionManager {

    static private transient Map<Integer, AbstractTransaction> currentTransaction = new ConcurrentHashMap<Integer, AbstractTransaction>();

    //单列方式运行,这个类对于外部没有意义,内核使用.
    final static private TransactionManager instance = new TransactionManager();

    public static TransactionManager getInstance() {
        return instance;
    }

    private TransactionManager() {

    }

    /**
     * 开始一个事务,当事务开始的时候jdbc连接将统一为一个
     *
     * @param transaction 事务对象
     */
    public void add(AbstractTransaction transaction) {
        currentTransaction.put(transaction.getTid(), transaction);
    }

    public void remove(int tid) {
        currentTransaction.remove(tid);
    }


    /**
     * 外部得到事务对象,通过连接池hashcode
     *
     * @param tid 通过连接id得到事务对象
     * @return 返回事务对象
     */
    public AbstractTransaction get(int tid) {
        return currentTransaction.get(tid);
    }

    public boolean containsKey(int tid) {
        return currentTransaction.containsKey(tid);
    }

    public void checkTransactionOvertime() {
        for (AbstractTransaction t : currentTransaction.values()) {
            //超时或关闭的事务对象将删除，
            if (t == null) continue;
            try {
                if (t.connection == null || t.connection.isClosed()) {
                    currentTransaction.remove(t.getTid());
                    continue;
                }
                if (System.currentTimeMillis() - t.getCreateTimeMillis() > t.getTimeout()) {
                    currentTransaction.remove(t.getTid());
                    if (!t.wasCommitted()) t.rollback();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    public int size() {
        return currentTransaction.size();
    }

    public boolean isEmpty() {
        return currentTransaction.isEmpty();
    }

    static public void debugPrint() {
        for (AbstractTransaction t : currentTransaction.values()) {
            //超时或关闭的事务对象将删除，
            System.out.println("tid=" + t.getTid());
        }
    }


}